package com.helin.helinhealth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;

/**
 * Spring Security 配置类
 *
 * <p>
 * 该配置类负责配置Spring Security的安全策略，包括URL访问权限、
 * 身份验证机制、会话管理等。
 * </p>
 *
 * <p>
 * 在生产环境中，集成了JWT认证过滤器，实现基于令牌的身份验证；
 * 在开发环境中，为方便测试，禁用了身份验证，允许所有请求通过。
 * </p>
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    /**
     * 环境变量，用于判断当前是开发环境还是生产环境
     */
    @Autowired
    private Environment environment;

    /**
     * JWT认证过滤器
     */
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * 配置CORS
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList(
                "http://localhost:[*]",
                "http://127.0.0.1:[*]",
                "http://172.20.10.10:5173",
                "https://helin.club"
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setExposedHeaders(Arrays.asList("Content-Disposition", "Content-Type", "Content-Length"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    /**
     * 配置安全过滤器链
     *
     * @param http HttpSecurity配置对象
     * @return 安全过滤器链
     * @throws Exception 配置异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 判断当前是否为开发环境
        boolean isDev = environment.getActiveProfiles().length > 0 &&
                environment.getActiveProfiles()[0].equals("dev");

        // 基础配置：禁用CSRF、配置为无状态会话
        http.csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        if (isDev) {
            // 开发环境：允许所有请求，方便调试
            http.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll());
        } else {
            // 生产环境：添加JWT过滤器，配置URL访问权限
            http.authorizeHttpRequests(authorize -> authorize
                            // 允许认证相关接口和Swagger文档无需身份验证
                            .requestMatchers("/api/auth/**",
                                    "/api/admin/login",
                                    "/api/admin/register",
                                    "/v3/api-docs/**",
                                    "/swagger-ui/**",
                                    "/swagger-resources/**",
                                    "/webjars/**",
                                    "/doc.html",
                                    "/favicon.ico").permitAll()
                            // 其他所有请求都需要身份验证
                            .anyRequest().authenticated()
                    )
                    // 添加JWT认证过滤器
                    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        }

        return http.build();
    }
}